package com.lin.mr.maizilaundry.base;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.lin.mr.maizilaundry.myapplication.MyApplication;


public class BaseActivity extends FragmentActivity {
	private long exitTime = 0;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		((MyApplication) getApplication()).addActivity(this);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		((MyApplication) getApplication()).removeActivity(this);
	}


	/**
	 * 捕捉返回事件按钮
	 *
	 * 因为此 Activity 继承 TabActivity 用 onKeyDown 无响应，所以改用 dispatchKeyEvent
	 * 一般的 Activity 用 onKeyDown 就可以了
	 */

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
				this.exitApp();
			}
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 退出程序
	 */
	private void exitApp() {
		// 判断2次点击事件时间
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			finish();
		}
	}

}
